// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/file/file_systems.h>
#include <tests/dwio/parquet/parquet_test_base.h>

using namespace kumo::pollux;
using namespace kumo::pollux::dwio::common;
using namespace kumo::pollux::parquet;

class SinkTest : public ParquetTestBase {
protected:
    static void SetUpTestCase() {
        memory::MemoryManager::testingSetInstance({});
        kumo::pollux::filesystems::registerLocalFileSystem();
    }
};

TEST_F(SinkTest, close) {
    auto rowType = ROW({"c0", "c1"}, {INTEGER(), VARCHAR()});
    auto batches = createBatches(rowType, 2, 3);
    auto filePath =
            fs::path(fmt::format("{}/test_close.txt", tempPath_->getPath()));
    auto sink = createSink(filePath.string());
    auto sinkPtr = sink.get();
    auto writer = createWriter(
        std::move(sink),
        [&]() {
            return std::make_unique<LambdaFlushPolicy>(
                kRowsInRowGroup, kBytesInRowGroup, [&]() { return false; });
        },
        rowType);

    for (auto &batch: batches) {
        writer->write(batch);
    }
    writer->flush();

    ASSERT_EQ(fs::file_size(filePath), sinkPtr->size());

    for (auto &batch: batches) {
        writer->write(batch);
    }

    // Close would flush
    writer->close();
    ASSERT_EQ(fs::file_size(filePath), sinkPtr->size());
}

TEST_F(SinkTest, abort) {
    auto rowType = ROW({"c0", "c1"}, {INTEGER(), VARCHAR()});
    auto batches = createBatches(rowType, 2, 3);
    auto filePath =
            fs::path(fmt::format("{}/test_abort.txt", tempPath_->getPath()));
    auto sink = createSink(filePath.string());
    auto sinkPtr = sink.get();
    auto writer = createWriter(
        std::move(sink),
        [&]() {
            return std::make_unique<LambdaFlushPolicy>(
                kRowsInRowGroup, kBytesInRowGroup, [&]() { return false; });
        },
        rowType);

    for (auto &batch: batches) {
        writer->write(batch);
    }
    writer->flush();

    auto size = sinkPtr->size();
    ASSERT_EQ(size, fs::file_size(filePath));

    for (auto &batch: batches) {
        writer->write(batch);
    }

    // Abort would not flush.
    writer->abort();
    ASSERT_EQ(size, fs::file_size(filePath));
}
